<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">事务管理</el-breadcrumb-item>
      <el-breadcrumb-item>今日事务</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="searchForm" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="medium" v-model="searchForm.name" placeholder="请输入姓名或号码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="medium" type="warning" icon="el-icon-plus" @click="registered">现场挂号</el-button>
<!--        <el-button v-show="addRegisteredVisible" size="medium" type="warning" icon="el-icon-plus" @click="addRegistered">加号</el-button>-->
        <el-button size="medium" type="warning" icon="el-icon-check" :disabled="isSubmit()" @click="submit">预约确认</el-button>
      </el-form-item>
      <el-form-item>
        <i class="el-icon-refresh" @click="refresh" style="cursor: pointer"></i>
      </el-form-item>
      <el-form-item style="float: right">
        <div><span style="color: #9c9c9c">当前时间段：</span>{{nowDate | formatDate2}}</div>
      </el-form-item>
      <el-form-item style="float: right;position: relative;right: 20px">
        <div>{{nowDate | formatDate}}</div>
      </el-form-item>
      <el-form-item style="float: right;position: relative;right: 20px">
        <el-button size="medium" type="info" :disabled="isPass()" @click="pass()">过号</el-button>
        <el-button size="medium"  :disabled="isEdit()" @click="handleEdit()">编辑</el-button>
        <el-button size="medium" type="danger"  :disabled="isDelete()" @click="deletePre()">删除</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table :header-cell-style="{fontSize: '17px'}" :cell-style="{fontSize: '20px'}" size="medium" :data="listData" ref="multipleTable" @selection-change="handleSelection" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="50">
      </el-table-column>
<!--      <el-table-column prop="id" label="ID" width="60">-->
<!--      </el-table-column>-->
<!--      <el-table-column prop="number" label="号码" min-width="75">-->
<!--      </el-table-column>-->
      <el-table-column prop="name" label="姓名" min-width="70">
      </el-table-column>
      <el-table-column prop="phone" label="电话" min-width="95">
      </el-table-column>
      <el-table-column prop="sex" label="性别" min-width="50">
      </el-table-column>
      <el-table-column prop="age" label="年龄" min-width="50">
      </el-table-column>
      <el-table-column prop="appointmentDate" label="预约日期" min-width="85">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.appointmentDate !==scope.row.created">
              {{scope.row.appointmentDate|spliceDate}}
            </span>
            <span v-if="scope.row.appointmentDate ===scope.row.created && scope.row.appointmentPeriodId !== 99">
              现场挂号
            </span>
            <span v-if="scope.row.appointmentPeriodId === 99">
              加号
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="appointmentPeriodId" label="预约时间段" min-width="90">
        <template slot-scope="scope" v-if="scope.row.appointmentPeriodId != null">
          <div>
            <span v-if="scope.row.appointmentPeriodId === 99">-</span>
            <span v-else>{{checkAppointmentPeriod(scope.row.appointmentPeriodId)}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="registrationTime" label="挂号时间" min-width="50">
        <template slot-scope="scope" v-if="scope.row.registrationTime != null">
          <div>{{scope.row.registrationTime|spliceDateMin}}</div>
        </template>
      </el-table-column>
      <el-table-column sortable prop="visitingTime" label="就诊时间" min-width="100">
        <template slot-scope="scope" v-if="scope.row.visitingTime != null">
          <div>{{scope.row.visitingTime|spliceDateMin}}</div>
        </template>
      </el-table-column>
<!--      <el-table-column sortable prop="completionTime" label="完成时间" min-width="100">-->
<!--        <template slot-scope="scope" v-if="scope.row.completionTime != null">-->
<!--          <div>{{scope.row.completionTime|spliceDateMin}}</div>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column sortable prop="state" label="状态" width="115" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.state === 0" style="text-align: center;font-size: 14px">{{scope.row.state|stateToString}}</div>
          <el-tag size="medium" v-if="scope.row.state !== 0" :type="stateColor(scope.row.state, scope.row.ispay)">{{scope.row.state,scope.row.ispay|stateToString}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button style="margin-left: -5px" size="medium" type="success" :disabled="isSuccess(scope.row.state)" @click="success(scope.$index, scope.row)">完成</el-button>
          <el-button v-if="scope.row.state !== 2" size="medium" type="warning" :disabled="isCall(scope.row.state, scope.row.ispay)" @click="call(scope.$index, scope.row)">叫号</el-button>
          <el-button v-if="scope.row.state === 2" size="medium" type="warning" @click="reCall(scope.$index, scope.row)">重新叫号</el-button>
<!--          <el-button  size="mini" type="info" :disabled="isPass(scope.row.state)" @click="pass(scope.$index, scope.row)">过号</el-button>-->
<!--          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>-->
<!--          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <!--    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>-->
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="100px" :model="editForm" ref="editForm">
        <el-form-item label="编辑对象">
          <el-select v-model="editForm.id"  @change="selectEditForm" placeholder="请选择编辑对象">
            <el-option
              v-for="(item,index) in checkMultipleTable"
              :key="item.id"
              :label="item.name+' '+item.number"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="就诊医生" prop="docterId">
          <el-select v-model="editForm.doctorId" placeholder="请选择就诊医生">
            <el-option
              v-for="item in doctorList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input size="medium" v-model="editForm.name" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input size="medium" v-model="editForm.phone" auto-complete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="editForm.sex" label="男">男</el-radio>
          <el-radio v-model="editForm.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input size="medium" v-model="editForm.age" auto-complete="off" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="editForm.state" placeholder="请选择状态">
            <el-option
              v-for="item in stateList"
              :key="item.id"
              :label="item.value"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态" prop="ispay">
          <span>{{editForm.ispay === 1?'已支付':'已退款'}}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="closeDialog">取消</el-button>
        <el-button size="medium" type="primary" :loading="loading" class="title" @click="editFormBtn('editForm')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 现场挂号 -->
    <el-dialog :title="registeredFormTitle" :visible.sync="registeredFormVisible" width="25%" @click="closeDialog">
      <el-form :model="registeredForm" :rules="rules" ref="registeredForm" label-width="100px">
        <el-form-item label="就诊医生" prop="docterId">
          <el-select v-model="registeredForm.person.doctorId" placeholder="请选择就诊医生">
            <el-option
              v-for="item in doctorList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input size="medium" v-model="registeredForm.person.name" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="person.phone">
          <el-input size="medium" v-model.number="registeredForm.person.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="registeredForm.person.sex" label="男">男</el-radio>
          <el-radio v-model="registeredForm.person.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input oninput="if(value>150)value=150;if(value<0)value=0" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" size="medium" v-model="registeredForm.person.age" auto-complete="off" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="就诊时间段" prop="appointmentPeriod">
          <el-select v-model="registeredForm.person.appointmentPeriod" placeholder="请选择就诊时间段">
            <el-option
              v-for="item in registeredTimeSlotList"
              :key="item.id"
              :label="item.timeSlot"
              :value="item.id"
              :disabled="item.number <= 0">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="closeDialog">取消</el-button>
        <el-button size="medium" type="primary" :loading="loading" class="title" @click="registeredFormBtn('registeredForm')">挂号</el-button>
      </div>
    </el-dialog>
    <!-- 加号 -->
    <el-dialog :title="addRegisteredFormTitle" :visible.sync="addRegisteredFormVisible" width="25%" @click="closeDialog">
      <el-form label-width="100px" :model="registeredForm" ref="editForm">
        <el-form-item label="就诊医生" prop="docterId">
          <el-select v-model="registeredForm.doctorId" placeholder="请选择就诊医生">
            <el-option
              v-for="item in doctorList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input size="medium" v-model="registeredForm.person.name" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input size="medium" v-model="registeredForm.person.phone" auto-complete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="registeredForm.person.sex" label="男">男</el-radio>
          <el-radio v-model="registeredForm.person.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input oninput="if(value>150)value=150;if(value<0)value=0" onkeyup="this.value=this.value.replace(/\D/g,'')" size="medium" v-model="registeredForm.person.age" auto-complete="off" placeholder="请输入年龄"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="closeDialog">取消</el-button>
        <el-button size="medium" type="primary" :loading="loading" class="title" @click="addRegisteredFormBtn()">加号</el-button>
      </div>
    </el-dialog>
    <!-- 确认预约界面 -->
    <el-dialog :title="submitFormTitle" :visible.sync="submitFormVisible" width="25%" @click="closeDialog">
      <el-form label-width="70px" :model="submitForm" ref="submitForm">
        <el-form-item label="预约号码" prop="preNumber">
          <el-input size="medium" v-model="submitForm.preNumber" auto-complete="off" placeholder="请输入预约号码"></el-input>
        </el-form-item>
      </el-form>
      <el-divider content-position="left">预约详情</el-divider>
      <div v-if="submitFormMsgVisible" style="margin-left: 0px;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);padding: 15px;line-height: 24px">
        <div><span>姓名：</span>{{ submitFormMsg.name }}</div>
        <div><span>性别：</span>{{ submitFormMsg.sex }}</div>
        <div><span>手机号：</span>{{ submitFormMsg.phone }}</div>
        <div><span>预约时间：</span>{{ submitFormMsg.appointmentDate }}</div>
        <div><span>预约时间段：</span>{{checkAppointmentPeriod(submitFormMsg.appointmentPeriodId)}}</div>
        <div><span>状态：</span>{{ submitFormMsg.state | stateToString }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="closeDialog">取消</el-button>
        <el-button size="medium" type="primary" :loading="loading" class="title" @click="submitFormBtn()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptList, deptSave, deptDelete } from '../../api/userMG'
import Pagination from '../../components/Pagination'
import {
  addRegistration,
  allDoctor,
  callNumber,
  carryOut,
  checkData, deletePre, getAllTimeSlot,
  getPreSearchList,
  getTimeSlotList, onSiteRegistration,
  passNumber,
  registered, updatePre
} from "../../api";
import {getCookie} from "../../utils/util";
export default {
  data() {
    // 手机号验证
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error('电话号码不能为空aaa'))
      }
      setTimeout(() => {

        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      submitFormVisible: false,
      registeredFormVisible: false,
      title: '修改',
      editForm: {},
      submitFormTitle: '预约确认',
      submitForm: {
        preNumber: ''
      },
      doctorList: [],
      timeSlotList: [],
      stateList: [
        { id: 0, value: '已预约' },
        { id: 1, value: '已挂号'},
        { id: 2, value: '就诊中'},
        { id: 3, value: '完成'},
        { id: 4, value: '过号'},
        { id: -1, value: '取消'},
      ],
      registeredFormTitle: '现场挂号',
      registeredForm: {
        person: {
          wxId: '',
          doctorId: '',
          name: '',
          phone: '',
          sex: '男',
          age: '',
          appointmentDate: '',
          appointmentPeriod: ''
        },
        desc: ''
      },
      registeredTimeSlotList: [],
      submitFormMsgVisible: false,
      submitFormMsg: {},
      addRegisteredFormTitle: '加号',
      addRegisteredVisible: false,
      addRegisteredFormVisible: false,
      ruleForm: {
        name: '',
        phone: '',
        email: '',
        age:''
      },
      // rules表单验证
      rules: {
        'person.phone': [
          {required: true, validator: checkPhone, trigger: 'blur' }
        ],
      },
      formInline: {
        draw: 1,
        length: 10,
        maxDate: '',
        minDate: '',
        orderCol: 'appointment_period_id',
        orderDir: 'asc',
        search: '%',
        start: 1
      },
      searchForm: {
        name: ''
      },
      // 删除部门
      seletedata: {
        ids: '',
        token: localStorage.getItem('logintoken')
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      successData: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      socket: {},
      socketAccount: '',
      nowDate: new Date(),
      checkMultipleTable: []
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    let _this = this
    let date = new Date()
    this.formInline.maxDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + ' 23:59:59'
    this.formInline.minDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + ' 00:00:00'
    this.getdata(this.formInline)

    allDoctor()
      .then(res => {
        _this.doctorList = res.result
      })
      .catch(err => {
        console.log(err)
      })
    getTimeSlotList({
        params: {
          dateStr: _this.formInline.minDate
        }
      })
      .then(res => {
        _this.timeSlotList = res.result.timeSlots
        // for (let i = 0; i < res.result.timeSlots.length;i++) {
        //   if (res.result.timeSlots[i].state === 1 && res.result.timeSlots[i].number > 0) {
        //     _this.timeSlotList.push(res.result.timeSlots[i])
        //   }
        // }
      })
      .catch(err => {
        console.log(err)
      })
    this.socketAccount = getCookie('account')
  },
  mounted() {
    this.openSocket()
    let _this = this;
    this.timer = setInterval(() => {
      _this.nowDate = new Date();
    }, 1000)
    setTimeout(() => {
      _this.addRegisteredVisibleFlag()
    }, 2000)
  },
  destroyed() {
    this.closeSocket()
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
    }
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取公司列表
    getdata(parameter) {
      this.loading = true
      let _this = this
      getPreSearchList({
        params: parameter
      })
        .then(res => {
          this.loading = false
          if (res.success == false) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.listData = []
            let successList = []
            let passList = []
            let delList = []
            let registeredList = []
            let list = []
            // this.listData = res.result.data
            for (let i = 0; i < res.result.data.length; i++) {
              if (res.result.data[i].state === 3) {
                successList.push(res.result.data[i])
              } else if (res.result.data[i].state === 4) {
                passList.push(res.result.data[i])
              } else if (res.result.data[i].state === -1 || res.result.data[i].ispay === -1) {
                delList.push(res.result.data[i])
              } else if (res.result.data[i].state === 1 || res.result.data[i].state === 2) {
                registeredList.push(res.result.data[i])
              } else {
                list.push(res.result.data[i])
              }
            }
            for (let i = 0; i < successList.length; i++) {
              this.listData.push(successList[i])
            }
            for (let i = 0; i < passList.length; i++) {
              this.listData.push(passList[i])
            }
            for (let i = 0; i < delList.length; i++) {
              this.listData.push(delList[i])
            }
            for (let i = 0; i < registeredList.length; i++) {
              this.listData.push(registeredList[i])
            }
            for (let i = 0; i < list.length; i++) {
              this.listData.push(list[i])
            }
            // 分页赋值
            this.pageparm.currentPage = this.formInline.page
            this.pageparm.pageSize = this.formInline.limit
            this.pageparm.total = res.recordsTotal
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('信息加载失败，请稍后再试！')
        })
    },
    refresh() {
      this.getdata(this.formInline)
      this.$message.success('刷新成功')
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    // 搜索事件
    search() {
      this.formInline.search = this.searchForm.name
      this.getdata(this.formInline)
    },
    submit: function () {
      let _this = this
      let array = []
      for(let i = 0; i < this.checkMultipleTable.length; i++) {
        array[i] = this.checkMultipleTable[i].number
      }
      this.$confirm('确认为预约号码为 ' + array + ' 进行预约确认操作吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = new URLSearchParams()
        params.append('preNumbers', array)
        registered(params)
          .then(res => {
            _this.loading = false
            if (res.success) {
              _this.getdata(this.formInline)
              _this.$message({
                type: 'success',
                message: '预约确认成功！'
              })
              _this.submitForm.preNumber = ''
              _this.sendMessage()
            } else {
              _this.$message({
                type: 'info',
                message: '预约确认失败'
              })
            }
          })
          .catch(err => {
            _this.submitFormVisible = false
            _this.loading = false
            _this.$message.error('预约确认失败，请稍后再试！')
          })
      }).catch(() => {
      })
      // this.submitFormVisible = true
    },
    handleSelection: function () {
      this.checkMultipleTable = this.$refs.multipleTable.selection
    },
    registered: function () {
      this.registeredFormVisible = true
      let _this = this
      getTimeSlotList({
        params: {
          dateStr: _this.formInline.minDate
        }
      })
        .then(res => {
          _this.registeredTimeSlotList = res.result.timeSlots
        })
        .catch(err => {
          console.log(err)
        })

      setTimeout(() => {
        let nowTimeSlotStr = ''
        if (this.nowDate.getMinutes() < 30) {
          nowTimeSlotStr = _this.nowDate.getHours() + ":00~" + _this.nowDate.getHours() + ":30"
        } else {
          nowTimeSlotStr = _this.nowDate.getHours() + ":30~" + (_this.nowDate.getHours() + 1) + ":00"
        }
        let flag = false
        let list = []
        for(let i = 0; i < _this.registeredTimeSlotList.length; i++) {
          if (_this.registeredTimeSlotList[i].timeSlot === nowTimeSlotStr) {
            flag = true
          }
          if (flag) {
            console.log(_this.registeredTimeSlotList[i])
            if (_this.registeredTimeSlotList[i].state === 1 && _this.registeredTimeSlotList[i].number > 0) {
              list.push(_this.registeredTimeSlotList[i])
            }
          }
        }
        let addNumber = {
          id: -1,
          timeSlot: '加号'
        }
        list.push(addNumber)
        _this.registeredTimeSlotList = list
      },1000)
    },
    addRegistered: function () {
      this.addRegisteredFormVisible = true
    },
    success: function (index, row) {
      let _this = this
      let params = new URLSearchParams()
      params.append('preId', row.id)
      carryOut(params)
        .then(res => {
          if (res.success) {
            this.getdata(this.formInline)
            this.$message({
              type: 'success',
              message: '完成！'
            })
            _this.sendMessage()
          } else {
            this.$message({
              type: 'info',
              message: '完成失败'
            })
          }
        })
        .catch(err => {
          this.$message({
            type: 'info',
            message: '完成失败'
          })
        })
    },
    call: function (index, row) {
      let _this = this
      let flag = false
      if (row.appointmentDate === row.registrationTime) {
        for (let i = 0; i < _this.listData.length; i++) {
          if (row.appointmentPeriodId === _this.listData[i].appointmentPeriodId && _this.listData[i].state !== 1 && row.id !== _this.listData[i].id) {
            flag = true
          }
          if (row.appointmentPeriodId === _this.listData[i].appointmentPeriodId && _this.listData[i].state === 1 && row.id === _this.listData[i].id) {
            flag = true
          }
          if (flag === false) {
            if (row.appointmentPeriodId === _this.listData[i].appointmentPeriodId && _this.listData[i].ispay === 1 && _this.listData[i].state === 1 && row.id !== _this.listData[i].id) {
              this.$confirm('前面有位顾客为网上预约且已挂号, 应先给网上预约的顾客就诊, 是否继续?', '提示', {
                confirmButtonText: '仍要继续',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let params = new URLSearchParams()
                params.append('preId', row.id)
                callNumber(params)
                  .then(res => {
                    if (res.success) {
                      this.getdata(this.formInline)
                      this.$message({
                        type: 'success',
                        message: '叫号成功！'
                      })
                      _this.sendMessage(row.number)
                    } else {
                      this.$message({
                        type: 'info',
                        message: '叫号失败'
                      })
                    }
                  })
                  .catch(err => {
                    this.$message({
                      type: 'info',
                      message: '叫号失败'
                    })
                  })
              }).catch(() => {
              });
              break;
            }
          }
        }
        if (flag) {
          let params = new URLSearchParams()
          params.append('preId', row.id)
          callNumber(params)
            .then(res => {
              if (res.success) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '叫号成功！'
                })
                _this.sendMessage(row.number)
              } else {
                this.$message({
                  type: 'info',
                  message: '叫号失败'
                })
              }
            })
            .catch(err => {
              this.$message({
                type: 'info',
                message: '叫号失败'
              })
            })
        }
      } else {
        let params = new URLSearchParams()
        params.append('preId', row.id)
        callNumber(params)
          .then(res => {
            if (res.success) {
              this.getdata(this.formInline)
              this.$message({
                type: 'success',
                message: '叫号成功！'
              })
              _this.sendMessage(row.number)
            } else {
              this.$message({
                type: 'info',
                message: '叫号失败'
              })
            }
          })
          .catch(err => {
            this.$message({
              type: 'info',
              message: '叫号失败'
            })
          })
      }
    },
    reCall: function (index, row) {
      this.sendMessage(row.number)
    },
    pass: function () {
      let _this = this
      let array = []
      for(let i = 0; i < this.checkMultipleTable.length; i++) {
        array[i] = this.checkMultipleTable[i].id
      }
      this.$confirm('确认为ID为 ' + array + ' 的事务进行过号操作吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = new URLSearchParams()
        params.append('preIds', array)
        passNumber(params)
          .then(res => {
            if (res.success) {
              this.getdata(this.formInline)
              this.$message({
                type: 'success',
                message: '过号成功！'
              })
              _this.sendMessage()
            } else {
              this.$message({
                type: 'info',
                message: '过号失败'
              })
            }
          })
          .catch(err => {
            this.$message({
              type: 'info',
              message: '过号失败'
            })
          })
      }).catch(() => {
      })
    },
    //显示编辑界面
    handleEdit: function() {
      this.editFormVisible = true
      this.editForm.id = this.checkMultipleTable[0].id
      this.editForm = JSON.parse(JSON.stringify(this.checkMultipleTable[0]))
    },
    selectEditForm: function (event) {
      for(let i = 0; i < this.checkMultipleTable.length; i++) {
        if (this.checkMultipleTable[i].id === event) {
          this.editForm = JSON.parse(JSON.stringify(this.checkMultipleTable[i]))
        }
      }

    },
    // 编辑
    editFormBtn() {
      let _this = this
      updatePre({
        'id': _this.editForm.id,
        'doctorId': _this.editForm.doctorId,
        'name': _this.editForm.name,
        'phone': _this.editForm.phone,
        'sex': _this.editForm.sex,
        'age': _this.editForm.age,
        'state': _this.editForm.state
      })
        .then(res => {
          _this.editFormVisible = false
          _this.loading = false
          if (res.success) {
            this.getdata(this.formInline)
            this.$message({
              type: 'success',
              message: '更新成功！'
            })
            _this.sendMessage()
          } else {
            this.$message({
              type: 'info',
              message: '更新失败'
            })
          }
        })
        .catch(err => {
          _this.editFormVisible = false
          _this.loading = false
          _this.$message.error('更新失败，请稍后再试！')
        })
    },
    // 现场挂号
    registeredFormBtn(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.registeredForm.person.appointmentDate = _this.formInline.minDate
          if (_this.registeredForm.person.appointmentPeriod === -1) {
            _this.addRegisteredFormBtn()
          } else {
            onSiteRegistration({
              // 'doctorId': _this.registeredForm.doctorId,
              // 'number': 1,
              'persons': [
                _this.registeredForm.person
              ]
            })
              .then(res => {
                console.log(res)
                _this.registeredFormVisible = false
                _this.loading = false
                if (res.success) {
                  // _this.registeredForm = {}
                  setTimeout(function () {
                    _this.registeredForm = {
                      person: {
                        wxId: '',
                        doctorId: '',
                        name: '',
                        phone: '',
                        sex: '男',
                        age: '',
                        appointmentDate: '',
                        appointmentPeriod: ''
                      },
                      desc: ''
                    }
                  },1000)
                  _this.getdata(_this.formInline)
                  _this.$message({
                    type: 'success',
                    message: '现场挂号成功！'
                  })
                  _this.submitForm.preNumber = ''
                  _this.sendMessage()
                } else {
                  _this.$message({
                    type: 'info',
                    message: '现场挂号失败'
                  })
                }
              })
              .catch(err => {
                _this.registeredFormVisible = false
                _this.loading = false
                _this.$message.error('现场挂号失败，请稍后再试！')
              })
          }
        } else {
          console.log('error!!');
          return false;
        }
      });
    },
    addRegisteredFormBtn: function () {
      let _this = this
      this.registeredForm.person.appointmentDate = this.formInline.maxDate
      this.registeredForm.person.appointmentPeriod = 99
      addRegistration({
        // 'doctorId': _this.registeredForm.doctorId,
        // 'number': 1,
        'persons': [
          _this.registeredForm.person
        ]
      })
        .then(res => {
          _this.registeredFormVisible = false
          _this.loading = false
          if (res.success) {
            // _this.registeredForm = {}
            setTimeout(function () {
              _this.registeredForm = {
                person: {
                  wxId: '',
                  doctorId: '',
                  name: '',
                  phone: '',
                  sex: '男',
                  age: '',
                  appointmentDate: '',
                  appointmentPeriod: ''
                },
                desc: ''
              }
            },1000)
            _this.getdata(_this.formInline)
            _this.$message({
              type: 'success',
              message: '加号成功'
            })
            _this.submitForm.preNumber = ''
            _this.sendMessage()
          } else {
            _this.$message({
              type: 'info',
              message: '加号失败'
            })
          }
        })
        .catch(err => {
          _this.addRegisteredFormVisible = false
          _this.loading = false
          _this.$message.error('加号失败，请稍后再试！')
        })
    },
    // 预约确认
    submitFormBtn: function () {
      let _this = this
      let params = new URLSearchParams()
      params.append('desc', '')
      params.append('isAppointment', 1)
      params.append('preNumber', _this.submitForm.preNumber)
      registered(params)
        .then(res => {
          _this.submitFormVisible = false
          _this.loading = false
          if (res.success) {
            _this.getdata(this.formInline)
            _this.$message({
              type: 'success',
              message: '预约确认成功！'
            })
            _this.submitForm.preNumber = ''
            _this.sendMessage()
          } else {
            _this.$message({
              type: 'info',
              message: '预约确认失败'
            })
          }
        })
        .catch(err => {
          _this.submitFormVisible = false
          _this.loading = false
          _this.$message.error('预约确认失败，请稍后再试！')
        })
    },
    // 删除公司
    deletePre() {
      let _this = this
      let array = []
      for(let i = 0; i < this.checkMultipleTable.length; i++) {
        array[i] = this.checkMultipleTable[i].id
      }
      this.$confirm('确认为ID为 ' + array + ' 的事务进行删除操作吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = new URLSearchParams()
        params.append('preIds', array)
        deletePre(params)
          .then(res => {
            if (res.success) {
              this.getdata(this.formInline)
              this.$message({
                type: 'success',
                message: '删除成功！'
              })
              _this.sendMessage()
            } else {
              this.$message({
                type: 'info',
                message: '删除失败'
              })
            }
          })
          .catch(err => {
            this.$message({
              type: 'info',
              message: '删除失败'
            })
          })
      }).catch(() => {
      })
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
      this.submitFormVisible = false
      this.registeredFormVisible = false
      this.addRegisteredFormVisible = false
    },
    openSocket: function () {
      let _this = this
      let socketUrl="https://mp.wwtsz.com:8813/ws/" + this.socketAccount;
      socketUrl = socketUrl.replace("https","wss").replace("http","ws");

      if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      }else{
        console.log("您的浏览器支持WebSocket");
        var lockReconnect = false;//避免重复连接
        var ws;
        var tt;
        //创建链接
        createWebSocket();
        //创建链接
        function createWebSocket() {
          try {
            _this.socket = new WebSocket(socketUrl);
            // 初始化链接
            init();
          } catch(e) {
            console.log('catch'+e);
            reconnect(socketUrl);
          }
        }

        /**
         * 初始化链接
         */
        function init() {
          _this.socket.onclose = function () {
            reconnect(socketUrl);
          };
          _this.socket.onerror = function() {
            reconnect(socketUrl);
          };
          _this.socket.onopen = function () {
            _this.socket.send("连接成功");
            //心跳检测重置
            heartCheck.start();
          };
          _this.socket.onmessage = function (event) {
            heartCheck.start();
            //拿到任何消息都说明当前连接是正常的
            //实时添加消息
            if (_this.isJson(event.data)) {
              let data = JSON.parse(event.data)
              if (data.contentText === 'update') {
                _this.getdata(_this.formInline)
              }
            }
          }
        }

        var lockReconnect = false;//避免重复连接
        //重试连接socket
        function reconnect(wsUrl) {
          if(lockReconnect) {
            return;
          };
          lockReconnect = true;
          //没连接上会一直重连，设置延迟避免请求过多
          tt && clearTimeout(tt);
          tt = setTimeout(function () {
            createWebSocket(wsUrl);
            lockReconnect = false;
          }, 180000);
        }
        //心跳检测
        var heartCheck = {
          timeout: 30000,
          timeoutObj: null,
          serverTimeoutObj: null,
          start: function(){
            var self = this;
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(function(){
              //这里发送一个心跳，后端收到后，返回一个心跳消息，
              //onmessage拿到返回的心跳就说明连接正常
              _this.socket.send("连接成功");
              self.serverTimeoutObj = setTimeout(function() {
                console.log(_this.socket);
                _this.socket.close();
              }, self.timeout);
            }, this.timeout)
          }
        }
      }
    },
    closeSocket: function() {
      this.socket.close()
    },
    sendMessage: function (number) {
      let _this = this
      if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      }else {
        _this.socket.send('{"toUserId":"' + 'all' + '","contentText":"' + 'update' + '"' + ',"number":"' + number + '"}');
      }
    },
    isJson: function (str) {
      if (typeof str == 'string') {
        try {
          let obj=JSON.parse(str);
          if(typeof obj == 'object' && obj ){
            return true;
          }else{
            return false;
          }

        } catch(e) {
          // console.log('error：'+str+'!!!'+e);
          return false;
        }
      }
      console.log('It is not a string!')
    },
    isSubmit: function () {
      let array = []
      for (let i = 0; i < this.checkMultipleTable.length; i++) {
        if (this.checkMultipleTable[i].state === 0) {
          array[i] = this.checkMultipleTable[i]
        }
      }
      if (array.length > 0) {
        return false
      }
      return true
    },
    isSuccess: function (state) {
      if (state === 2 || state === 4) {
        return false
      }
      return true
    },
    isCall: function (state, ispay) {
      if (ispay === -1) {
        return true
      }
      if (state === 1) {
        return false
      }
      return true
    },
    isPass: function (state) {
      let array = []
      for (let i = 0; i < this.checkMultipleTable.length; i++) {
        if (this.checkMultipleTable[i].state === 1 || this.checkMultipleTable[i].state === 2) {
          array[i] = this.checkMultipleTable[i]
        }
      }
      if (array.length > 0) {
        return false
      }
      return true
    },
    isEdit: function () {
      let array = []
      for (let i = 0; i < this.checkMultipleTable.length; i++) {
        array[i] = this.checkMultipleTable[i]
      }
      if (array.length > 0) {
        return false
      }
      return true
    },
    isDelete: function () {
      let array = []
      for (let i = 0; i < this.checkMultipleTable.length; i++) {
        array[i] = this.checkMultipleTable[i]
      }
      if (array.length > 0) {
        return false
      }
      return true
    },
    checkAppointmentPeriod: function (appointmentPeriodId) {
      for (let i = 0; i < this.timeSlotList.length; i++) {
        if (this.timeSlotList[i].id === appointmentPeriodId) {
          return this.timeSlotList[i].timeSlot
        }
      }
    },
    checkLoad: function ({rowIndex}) {
      console.log(rowIndex)
    },
    stateColor: function (state, ispay) {
      if (ispay === -1) {
        return 'danger'
      }
      if (state === 1) {
        return
      }
      if (state === 2) {
        return 'warning'
      }
      if (state === 3) {
        return 'success'
      }
      if (state === 4) {
        return 'info'
      }
      if (state === -1) {
        return 'danger'
      }
    },
    addRegisteredVisibleFlag: function () {
      let startFlag = false
      for (let i = 0; i < this.timeSlotList.length; i++) {
        if (this.timeSlotList[i].timeSlot !== formatDateString(this.nowDate)) {
          this.addRegisteredVisible = true
        }
        if (this.timeSlotList[i].timeSlot === formatDateString(this.nowDate)) {
          startFlag = true
        }
        if (startFlag) {
          if (this.timeSlotList[i].number <= 0) {
            this.addRegisteredVisible = true
          } else {
            this.addRegisteredVisible = false
          }
        }
      }

      function formatDateString(date) {
        function PrefixZero(num, n) {
          return (Array(n).join(0) + num).slice(-n);
        }
        if (date.getMinutes() < 30) {
          return PrefixZero(date.getHours(), 2) + ":00~" + PrefixZero(date.getHours(), 2) + ":30"
        } else {
          return PrefixZero(date.getHours(), 2) + ":30~" + PrefixZero(date.getHours() + 1, 2) + ":00"
        }
      }
    },
  },
  filters: {
    stateToString: function (state, ispay) {
      if (ispay === -1) {
        return "已取消(退款)"
      }else {
        switch (state) {
          case 0: return "已预约";
          case 1: return "已挂号";
          case 2: return "就诊中";
          case 3: return "已完成";
          case 4: return "过号";
          case -1: return "已取消";
          default: return "/"
        }
      }
    },
    spliceDate: function (value) {
      return value.substr(0,10)
    },
    spliceDateMin: function (value) {
      return value.substr(10, 6)
    },
    formatDate: function (date) {
      function PrefixZero(num, n) {
        return (Array(n).join(0) + num).slice(-n);
      }
      return date.getFullYear() + "年" + PrefixZero(date.getMonth() + 1, 2) + "月" + PrefixZero(date.getDate(), 2) + "日 " + PrefixZero(date.getHours(), 2) + ":" + PrefixZero(date.getMinutes(), 2) + ":" + PrefixZero(date.getSeconds(), 2)
    },
    formatDate2: function (date) {
      function PrefixZero(num, n) {
        return (Array(n).join(0) + num).slice(-n);
      }
      if (date.getMinutes() < 30) {
        return PrefixZero(date.getHours(), 2) + ":00~" + PrefixZero(date.getHours(), 2) + ":30"
      } else {
        return PrefixZero(date.getHours(), 2) + ":30~" + PrefixZero(date.getHours() + 1, 2) + ":00"
      }
    },
    formatAppointmentPeriod: function (value) {
      let _this = this
      return value
    },
  },
  watch: {
    'submitForm.preNumber'() {
      let _this = this
      if (this.submitForm.preNumber.length === 8) {
        checkData({
          params: {
            preNumber: _this.submitForm.preNumber
          }
        })
          .then(res => {
            if (res.success) {
              _this.submitFormMsgVisible = true
              _this.submitFormMsg = res.result
            } else {
              _this.submitFormMsgVisible = false
            }
          })
          .catch(err => {

          })
      } else {
        _this.submitFormMsgVisible = false
      }
    },
    'searchForm.name'() {
      let _this = this
      if (this.searchForm.name === '' || this.searchForm.name == null) {
        _this.search()
      }
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.tableBox{
  font-size: 16px;
}
</style>
